<?php
namespace app\admin\classes;

use core\Api;
use core\V;
use core\Res;
use core\Func;


/**
 * 基础管理类
 */
class BasicManager extends \C {

  static $model;
  // 本页地址
  static $hash="";
  // 展开的菜单
  static $menuHash="";
  // 首页的模板文件
  static $view_index="";
  // 首页的内容模板
  static $tpl_index="";
  // 编辑页的模板文件
  static $view_edit="";
  // 编辑页的内容模板
  static $tpl_edit="";
  // 添加页的模板文件
  static $view_add="";
  // 添加页的内容模板
  static $tpl_add="";

  // 按钮区域宽度
  static $actArea_width="100";

  // 变量列表
  static $var="id,remark";
  // 页面标题设置
  static $title=[
    "index"=>[
      "title"=>"",
      "breadcrumb"=>[],
      "subtitle"=>"",
    ],
    "add"=>[
      "title"=>"",
      "breadcrumb"=>[],
      "subtitle"=>"",
    ],
    "edit"=>[
      "title"=>"",
      "breadcrumb"=>[],
      "subtitle"=>"",
    ],
  ];
  public function getHash(){
    return Func::getHash();
  }
  public function add_body(){
    return $this->edit_body();
  }
  public function edit_body(){
    return "";
  }
  public function index_body(){
    return "";
  }

  public function search_body(){
    return "";
  }
  public function index_act(){

    return '
    <el-table-column
      fixed="right"
      label="操作"
      align="right"
      header-align="right"
      width="'.static::$actArea_width.'">
      <template slot-scope="scope">
        ___btn___
        <el-button class="tablebtn-edit" @click="doEdit(scope.row.id)" type="text" size="small">编辑</el-button>
        <el-button class="tablebtn-del" @click="doDel(scope.row.id)" type="text" size="small">删除</el-button>
      </template>
    </el-table-column>
    ';
  }

  public function getlist_search(&$query){
    $form=input("form");
    if (!empty($form)){
      if (is_array($form)){
        foreach ($form as $key => $value) {
          if (!empty($value)){
            $query->where($key,"like","%$value%");
          }
        }
      }
    }
  }
  public function getlist_filter(&$item){
    $vars=Func::str2arr(static::$var);
    $result=[];
    foreach ($vars as $key) {
      $key=trim($key);
      $result[$key]=$item->getAttr($key);
    }
    return $result;
  }
  // 添加页面输出时对VueData变量进行预处理
  public function add_filter(){
    return [
      "id"=>"",
    ];
  }
  // 编辑页面输出时对VueData变量进行预处理
  public function edit_filter(&$item){
    return [];
  }
  // 保存的时候对变量进行过滤筛选
  public function save_filter(&$data){
    return $data;
  }
  // 数据库中是否已经存在相同记录
  protected function db_has($data,$key){
    $result=false;
    $db=static::$model::where("status",1)
             ->where($key,$data[$key]);
    if (!empty($data["id"])){
      $db->where("id","<>",$data["id"]);
    }

    if ($db->count()>0) $result=true;
    return $result;
  }
  // 根据pid生成tree
  public function makeTree($data,$pid=0,$level=0){
    $result=[];
    foreach($data as $key=>$v){
        if($v['pid']==$pid){
            $item=[
              "id"=>(string)$v["id"],
              "pid"=>(string)$v["pid"],
              "level"=>(string)$level,
              "value"=>(string)$v["id"],
              "label"=>(string)$v["name"],
            ];

            $children=$this->makeTree($data,$v['id'],$level+1);
            if (!empty($children)){
              $item["children"]=$children;
            }
            $result[]=$item;
        }
    }
    return $result;
  }

  // 首页
  public function index(){

    $this->wapper([
      "show"=>true,
      "title"=>static::$title["index"]["title"],
      "breadcrumb"=>static::$title["index"]["breadcrumb"],
      "panel"=>isset(static::$title["index"]["panel"])?static::$title["index"]["panel"]:'<a href="'.static::$hash.'/add" class="btn waves-effect waves-light btn-success">添加</a>',
      "subtitle"=>static::$title["index"]["subtitle"],

    ]);

    $this->VD([
      "apiBase"=>static::$hash
    ]);

    if (!empty(static::$view_index)){
      return view(static::$view_index,$this->VD());
    }else{
      if (empty(static::$tpl_index)) static::$tpl_index=BasicManagerTemplet::index();
      return $this->displayout("index",static::$tpl_index,$this->VD());
    }


  }

  // 获取列表
  public function getlist(){

    $page=input("page","1");
    $pagesize=input("pagesize","10");

    $item= static::$model::where("status",1);

    // 处理筛选条件
    $this->getlist_search($item);

    $total=$item->count();

    $itemList=$item->page($page,$pagesize)
    ->order("create_at","desc")
    ->all();

    $list=[];
    $vars=Func::str2arr(static::$var);
    foreach ($itemList as $item) {

      $result=[];
      foreach ($vars as $key) {
        $key=trim($key);
        $result[$key]=$item->getAttr($key);
      }
      $result2=$this->getlist_filter($item);

      $list[]=array_merge($result,$result2);

    }

    $result=[
      "total"=>$total,
      "list"=>$list,
    ];

    Api::ok($result);


  }
  // 添加页面
  public function add(){


    if (empty(static::$menuHash)){
      static::$menuHash=static::$hash.'/add';
    }

    $this->wapper([
      "show"=>true,
      "title"=>static::$title["add"]["title"],
      "breadcrumb"=>static::$title["add"]["breadcrumb"],
      "panel"=>'<a id="gotomanage" href="'.static::$hash.'/index" class="btn waves-effect waves-light btn-success">管理</a>',
      "subtitle"=>static::$title["add"]["subtitle"],

    ]);

    $this->VD([
      "apiBase"=>static::$hash
    ]);

    $list=[];
    $vars=Func::str2arr(static::$var);
    $result=["_act"=>"add"];
    foreach ($vars as $key) {
      $key=trim($key);
      $result[$key]="";
    }
    $result2=$this->add_filter();
    $list=array_merge($result,$result2);



    $this->VueData($list);

    if (!empty(static::$view_add)){
      return view(static::$view_add,$this->VD());
    }else{
      if (empty(static::$tpl_add)) static::$tpl_add=BasicManagerTemplet::add();
      return $this->displayout("add",static::$tpl_add,$this->VD());
    }

  }
  // 编辑页面
  public function edit(){


    if (empty(static::$menuHash)){
      static::$menuHash=static::$hash.'/index';
    }

    $id=input("id");
    empty($id) and $this->error('id错误');



    $this->wapper([
      "show"=>true,
      "title"=>static::$title["edit"]["title"],
      "breadcrumb"=>static::$title["edit"]["breadcrumb"],
      "panel"=>'<a id="gotomanage" href="'.static::$hash.'/index" class="btn waves-effect waves-light btn-success">管理</a>',
      "subtitle"=>static::$title["edit"]["subtitle"],

    ]);

    $this->VD([
      "apiBase"=>static::$hash
    ]);

    $item=static::$model::get($id);
    if (!$item){
      $this->error('id错误');
    }

    $list=[];
    $vars=Func::str2arr(static::$var);
    $result=["_act"=>"edit"];
    foreach ($vars as $key) {
      $key=trim($key);
      $result[$key]=$item->getAttr($key);
    }
    $result2=$this->edit_filter($item);
    $list=array_merge($result,$result2);

    $this->VueData($list);


    if (!empty(static::$view_edit)){
      return view(static::$view_edit,$this->VD());
    }else{
      if (empty(static::$tpl_edit)) static::$tpl_edit=BasicManagerTemplet::edit();
      return $this->displayout("edit",static::$tpl_edit,$this->VD());
    }
  }
  // 保存api
  public function save(){

    $data=V::get(static::$var);
    $data=$this->save_filter($data);


    $id=$data["id"];
    if (empty($id)){
      $news=static::$model::create($data,true);
    }else{
      $news=static::$model::get($id);
      if ($news){
        $news->allowField(true)->update($data);
      }else{
        Api::error('id错误');
      }
    }

    Api::ok('保存成功');
  }
  public function delete(){
    $id=input("id");
    empty($id) and Api::error('id错误');

    $item=static::$model::get($id);
    if ($item){
      $item->status=2;
      $item->save();
      $item->delete();
      Api::ok("删除完成");
    }else{
      Api::error('遇到错误');
    }

  }
  // 重写display方法
  public function displayout($key,$t="",$v=[],$c=[]){

    if ($key=="add"){
      $t=str_replace("___add___",$this->add_body(),$t);
    }elseif ($key=="edit") {
      $t=str_replace("___edit___",$this->edit_body(),$t);
    }else{
      $t=str_replace("___index___",$this->index_body(),$t);
      $t=str_replace("___search___",$this->search_body(),$t);
      $t=str_replace("___indexact___",$this->index_act(),$t);
    }


    $t=str_replace("___vue___",$this->getVD("___vue___"),$t);
    $t=str_replace("___css___",$this->getVD("___css___"),$t);
    $t=str_replace("___btn___",$this->getVD("___btn___"),$t);


    if (!empty(static::$menuHash)){
      $this->menuActive(static::$menuHash);
    }

    return $this->display($t,$v,$c);
  }

}

/**
 * 模板
 */
class BasicManagerTemplet
{
  static function index(){
    $html=<<<'CODE'
    {layout name="/public/layout_index" /}

    <style>
    .is-right > .cell{
      display:inline;
    }
    ___css___
    </style>

    <div id="app" v-cloak>

      <c-card title="{$wapper['title']}" subtitle="{$wapper['subtitle']}">


        <el-form :inline="true" :model="form" size="mini" @submit.prevent="return false">
          ___search___

          <el-form-item>
            <el-button class="btn-info waves-effect waves-light" type="primary" @click="Search">查询</el-button>
          </el-form-item>
        </el-form>


        <el-table
          :data="list"
          style="width: 100%"
        >

          ___index___

          ___indexact___


        </el-table>

        <el-pagination
          class="mt-5 float-right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currentPage"
          :page-sizes="[10, 20, 50, 100, 300, 500]"
          :page-size="page.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>


      </c-card>


    </div>



    <script>
    var mixin = {
      ___vue___
    };
    var base_mixin={
      data:{
        apiBase:"{$apiBase}",
        form:{},
        page: {
          currentPage:1,
          total: 0,
          pagesize: 10
        },
        list:[]

      },
      methods: {
        init(){
          this.Search();
        },
        Search: function(){
          var that=this;
          var postData={
            "form": this.form,
            "page": this.page.currentPage,
            "pagesize": this.page.pagesize
          };
          APP.ajax(this.apiBase+"/getlist",postData,function(msg){
            if (msg.result){
              that.page.total=parseInt(msg.data.total);
              that.list=msg.data.list;
            }else{
              APP.alert(msg.data);
            }
          });
        },
        doEdit:function(id){
          APP.goto(this.apiBase+"/edit/id/"+id);
        },
        doDel:function(id){
          var that=this;
          APP.confirm("确定要删除吗？",function(){
            APP.ajax(that.apiBase+"/delete",{id:id},function(msg){
              if (msg.result){
                if (msg.data) APP.alert(msg.data,true);
                that.Search();
              }else{
                APP.alert(msg.data);
              }
            });
          });
        },
        handleSizeChange: function(val) {
          this.page.pagesize=val;
          this.Search();
        },
        handleCurrentChange: function(val) {
          this.page.currentPage=val;
          this.Search();
        }

      },
      mounted(){
        var that=this;
        this.$nextTick(function () {
          that.init();
        })
      }
    };
    var main=new Vue({
      el:"#app",
      mixins: [base_mixin,mixin],

    });

    </script>


CODE;
    return $html;

  }

static function add(){
  $htmls=static::edit();
  $htmls=str_replace("___edit___","___add___",$htmls);
  return $htmls;
}

static function edit(){

  $html=<<<'CODE'
  {layout name="/public/layout_index" /}

  <style>
  ___css___
  </style>

  <div id="app" v-cloak>

    <c-card title="{$wapper['title']}" subtitle="{$wapper['subtitle']}">


      <el-form ref="form" :model="form" label-width="80px" @submit.prevent="return false">

        ___edit___

        <el-form-item>
          <el-button class="btn-info waves-effect waves-light" type="primary" @click="onSubmit">保存</el-button>
        </el-form-item>
      </el-form>


    </c-card>

  </div>


  <script>
  var mixin = {
    ___vue___
  };
  var base_mixin={
    data:{
      apiBase:"{$apiBase}",
      form:{$vue_data|raw}
    },
    methods: {
      onSubmit() {

        var that=this;
        APP.ajax(this.apiBase+"/save",this.form,(res)=>{
          if (res.result){
            APP.alert(res.data,true);
            if (that.onFinish){
              that.onFinish(res);
            }else{
              if (that.form._act=="add"){
                if (that.onAddFinish){
                  that.onAddFinish(res);
                }else{
                  APP.reload(1000);
                }
              }else{
                if (that.onEditFinish){
                  that.onEditFinish(res);
                }else{
                  APP.goto($("#gotomanage").attr("href"),1000);
                }
              }
            }



          }else{
            APP.alert(res.data);
          }
        });
      }
    }
  };
  var main=new Vue({
    el:"#app",
    mixins: [base_mixin,mixin],

  });

  </script>

CODE;
    return $html;
  }
}
